#include<iostream>

#define N 10

int fill_array(int [], int);

int find_dis(int [], int, int);

int down_sort(int [], int, int);

int find_binary(int [], int, int, int);

void show_res(int, int, int);

void show_array(int [], int);

int main(){
    int array[N] {0};
    int dist = 0;
    int pos = -1;

    fill_array(array, N);

    std::cout << "please enter the distinction:\t";
    std::cin >> dist;
    std::cout << std::endl;

    pos = find_dis(array, dist, N);
    show_res(pos, N, dist);
    show_array(array, N);

    pos = -1;
    down_sort(array, 0, N);
    std::cout << "the sorted array is" << std::endl;
    show_array(array, N);

    pos = find_binary(array, 0, N, dist);
    show_res(pos, N, dist);

    getchar();
    getchar();

    return 0;
}

int fill_array(int arr[], int len){
    std::cout << "please enter the array" << std::endl;
    for (int i = 0; i < len; i++){
        std::cin >> arr[i];
    }
}

int find_dis(int arr[], int dist, int len){
    int pos = -1;
    for(int i = 0; i < len; i++){
        if(arr[i]==dist){
            pos = i;
            break;
        }
    }
    return pos;
}

int find_binary(int arr[], int start = 0, int end = 0, int dist=0){
    if(start < 0 || end <=0){
        std::cout << "range error \n";
        return -1;
    }

    int middle = 0;
    while(true){
        if(arr[start] == dist){
            middle = start;
            // std::cout << "e-the NO. of " << dist << " is" << middle << std::endl;
            return middle;
        }
        if(arr[end] == dist){
            middle = end;
            // std::cout << "s-the NO. of " << dist << " is" << middle << std::endl;
            return middle;
        }

        if(start == end) break;

        middle = (start + end) / 2;
        if(arr[middle] > dist){
            start = middle;
        }else {
            end = middle;
        }
    }

    std::cout << "not found" << std::endl;
    return -1;
}

int down_sort(int array[], int start=0, int end=0){
    if(start < 0 || end <=0){
        std::cout << "range error \n";
        return -1;
    }

    int temp = 0;
    for (int i = end-1; i > start; i--)
    {
        for(int j = start; j < i; j ++){
            if(array[j] < array[j+1]){
                temp = array[j];
                array[j] = array[j+1];
                array[j+1] = temp;
            }
        }
    }
    return 0;
}

void show_res(int pos, int len, int dist){
    if(pos < len && pos >= 0){
        std::cout << "the NO. of " << dist << " is " << pos << std::endl;
    }else {
        std::cout << "the distinction not found" << std::endl;
    }
}

void show_array(int array[], int len){
    for (int i = 0; i < len; i++){
        std::cout << array[i] << " ";
    }
    std::cout << std::endl;
}